package org.jeecg.modules.FinanceModule.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;

import org.jeecg.modules.FinanceModule.entity.*;
import org.jeecg.modules.FinanceModule.service.FinanceService;
import org.jeecg.modules.zonglzp.entity.User;
import org.jeecg.modules.zonglzp.entity.store;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;

@RestController
@RequestMapping("/Finance")
public class FinanceController {


    @Autowired
    FinanceService service;


    /*
    唉 查询客户往来中公司列表
     */
    @GetMapping("/companyList")
    public Result<?> getcompanyList(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "status", defaultValue = "10") int status,
            String realName,
            String companyName,  //通过公司名称模糊查询
            String aboutPhone //通过公司电话查询
    ) {
        Page<CompanyEntity> page = new Page<CompanyEntity>(pageNo, pageSize);
        IPage<CompanyEntity> pageList = service.getcompanyList(page,companyName,aboutPhone,realName,status);
        return Result.ok(pageList);
    }



    /*
    查询客户的充值明细
     */
    @GetMapping("/FinanceWaterlist")
    public Result<?> getFinanceWaterlist(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "userId") String userId,
            String date,
            String starttime,
            String endtime
    ) {
        if(date!=null)
        date=date.substring(1,11);

        Page<FinancialWaterEntity> page = new Page<FinancialWaterEntity>(pageNo, pageSize);
        IPage<FinancialWaterEntity> pageList = service.getFinanceWaterlist(page, userId,date,starttime,endtime);

        return Result.ok(pageList);
    }


    /*
    查询客户的业务流水，订单
     */
    @GetMapping("/BusinessWaterlist")
    public Result<?> getBusinessWaterlist(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "userId") String userId
    ) {
        Page<BusinessWaterEntity> page = new Page<BusinessWaterEntity>(pageNo, pageSize);
        IPage<BusinessWaterEntity> pageList = service.getBusinessWaterlist(page, userId);
        return Result.ok(pageList);
    }

    /*
     查询该公司下所有人的业务流水
     */
    @GetMapping("/getCompanyBusinessList")
    public Result<?> getCompanyBusinessList(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "companyCode") String companyCode,
            @RequestParam(name = "isAfter") int isAfter
    ) {
        Page<BusinessWaterEntity> page = new Page<BusinessWaterEntity>(pageNo, pageSize);
        IPage<BusinessWaterEntity> pageList = service.getCompanyBusinessList(page, companyCode,isAfter);
        return Result.ok(pageList);
    }

    /*
    充值操作
     */
    @GetMapping("/addMoney")
    public Result<?> addMoney(
            @RequestParam(name = "id") int userId,
            @RequestParam(name = "money") String money
    ) {


        try {
            //先查询已有该用户已有的金额
            String oldmoney = service.getoldmoney(userId);

            //更新用户的余额
            double newmoneyInt = Double.parseDouble(oldmoney) + Double.parseDouble(money);
            service.updateAccountBalance(userId, String.valueOf(newmoneyInt));

            //往财务流水明细表里插入一条数据
            service.insertAddmoneyWater(userId, money);
            return Result.ok("充值成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("充值失败");
        }
    }

    /*
     撤回充值的金额的操作
     */
    @GetMapping("/rollbackMoney")
    public Result<?> rollbackMoney(
            @RequestParam(name = "userId") int userId,
            @RequestParam(name = "id") int id,
            @RequestParam(name = "money") String money,
            @RequestParam(name = "type") int type

    ) {
        int count = service.rollbackMoney(userId, id, money,type);

        if (count > 0) {
            return Result.ok("撤回成功！");
        } else {
            return Result.error("撤回失败!");
        }
    }


    /*
    客户往来查看详情中 公司的详情
     */
    @GetMapping("/getcompanydetail")
    public Result<?> getcompanydetail(
            @RequestParam(name = "companyCode") String companyCode
    ) {
        CompanyEntity entity = service.getcompanydetail(companyCode);

        if (entity.getIsMonth() == 0) {
            entity.setIsmouthString("普通用户");
        } else {
            entity.setIsmouthString("月结用户");
        }
        System.out.println(entity.getIsMonth()+"打印看一下嘛"+entity.getIsmouthString());
        return Result.ok(entity);
    }


    /*
    那就让我查询这个公司编码下所有的员工吧
     */
    @GetMapping("/getcompanystaff")
    public Result<?> getcompanystaff(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "companyCode") String companyCode
    ) {
        Page<User> page = new Page<User>(pageNo, pageSize);
        IPage<User> pageList = service.getcompanystaff(page, companyCode);
//        List<User>  staffList=service.getcompanystaff(companyCode);
        return Result.ok(pageList);
    }

    /*
     那就查询这个公司下所有的门店吧
     */
    @GetMapping("/getcompanystore")
    public Result<?> getcompanystore(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "companyId") String companyId
    ) {
        Page<store> page = new Page<store>(pageNo, pageSize);
        IPage<store> pageList = service.getcompanystore(page, companyId);
        return Result.ok(pageList);
    }

    /*
    查询这个公司的品牌标列表
     */
    @GetMapping("/getcompanylabel")
    public Result<?> getcompanylabel(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "companyId") String companyId
    ) {

        Page<Map<String, Object>> page = new Page<Map<String, Object>>(pageNo, pageSize);
        IPage<Map<String, Object>> pageList = service.getcompanylabel(page, companyId);
        if (pageList != null) {
            for (int i = 0; i < pageList.getRecords().size(); i++) {
                pageList.getRecords().get(i).put("create_time", pageList.getRecords().get(i).get("create_time").toString().substring(0, 19));
            }
        }
        return Result.ok(pageList);
    }


    /*
     系统反冲操作
     先往系统反冲表中插入一条数据
     然后往财务表流水中插入金额记录
     然后增加一下人员的金额
     */
    @GetMapping("/Systemrecoil")
    public Result<?> Systemrecoil(
            @RequestParam(name = "userId") String userId,  //用户id
            @RequestParam(name = "recoilType") int recoilType,  //反冲类型
            @RequestParam(name = "recoilMoney") String recoilMoney, //反冲金额
           String factoryResponsibility, //加工厂责任
            String platformResponsibility, //平台责任
           String remark //备注
    ) {


        System.out.println("看一看反冲类型"+recoilMoney);
        try {
            if (recoilMoney == null || "".equals(recoilMoney)) {
                return Result.error("参数填写不完整，请重写");
            }
            if( factoryResponsibility == null || "".equals(factoryResponsibility)
                    || platformResponsibility == null || "".equals(platformResponsibility)){
                factoryResponsibility="0";
                platformResponsibility="0";
            }
            //往反冲表中插入一条数据
            service.insertrecoiltable(userId, recoilType, recoilMoney, factoryResponsibility, platformResponsibility, remark);

            //往财务流水表中插入一条
            service.insertcaiwuliushuibyfanchon(userId, recoilMoney,recoilType,remark);

            //然后将反冲的金额加到客户原来的金额上
            //先查询已有该用户已有的抵扣额度
             String oldmoney = service.getoldmoney(Integer.parseInt(userId));

            //旧的余额
            BigDecimal money1=new BigDecimal(oldmoney);
            //反冲金额
            BigDecimal money2=new BigDecimal(recoilMoney);


            //查询月结额度
//            String yuejieedu=service.getyuejieedubyid(Integer.parseInt(userId));
//           if(yuejieedu==null){
//               yuejieedu="0";
//           }
            //查询抵扣额度
            String shengyuedu=service.getshengyuedu(Integer.parseInt(userId));
            if(shengyuedu==null){
                shengyuedu="0";
            }
            BigDecimal money3=new BigDecimal(shengyuedu);

            if(recoilType==2||recoilType==3){
                service.updaterealAccountBalance(Integer.parseInt(userId), String.valueOf( money1.add(money2)));
            }else {
                service.updateAccountBalance(Integer.parseInt(userId), String.valueOf( money3.add(money2)));
            }




            return Result.ok("反冲成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("失败，请重试");
        }
    }




    /*
    查询客户的开票记录
     */

    @GetMapping("/KehukaipiaoList")
    public Result<?> KehukaipiaoList(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "userId") String userId
    ) {
        Page<InvoiceEntity> page = new Page<InvoiceEntity>(pageNo, pageSize);
        IPage<InvoiceEntity> pageList = service.getKehukaipiaoList(page, userId);
        return Result.ok(pageList);
    }

    /*
    开票页面的公司详情
     */
    @GetMapping("/KehukaipiaoDetail")
    public Result<?> KehukaipiaoDetail(
            @RequestParam(name = "userId") String userId
    ){
        CompanyEntity  entity=service.getKehukaipiaoDetail(userId);
        //获取已开票金额
        String yiInvoicedmoney=service.getInvoicedmoneybyuserId(userId,1);
        if(yiInvoicedmoney==null)
            yiInvoicedmoney="0.0";
        //获取未开票金额
        String weiInvoicedmoney=service.getInvoicedmoneybyuserId(userId,0);
        if(weiInvoicedmoney==null)
            weiInvoicedmoney="0.0";
        entity.setYiInvoicedmoney(yiInvoicedmoney);
        entity.setWeiInvoicedmoney(service.getNoEnterMoney(userId));
        return Result.ok(entity);
    }



    /*
    新增开票记录
     */
    @PostMapping("/addInvoice")
    public Result<?> addInvoice(
         @RequestBody   InvoiceEntity entity
    ){
        try {
            String weikaipiaomoney=service.getNoEnterMoney(entity.getUserId());

             if(Double.parseDouble(weikaipiaomoney)<Double.parseDouble(entity.getInvoiceAmount())){
                 return Result.ok("新开票金额不能大于未开票金额");
             }
            int count=service.addInvoice(entity);
             service.updateUserNoEnterMoney(entity.getUserId(),Double.parseDouble(weikaipiaomoney)-Double.parseDouble(entity.getInvoiceAmount()));
            return Result.ok("增加成功!");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("信息不完整,请重新填写!");
        }
    }

    /*
    新增对账记录
     */
    @PostMapping("/addReconciliation")
    public Result<?> addReconciliation(
            @RequestBody     ReconciliationEntity entity
    ){
        int count=service.addReconciliationEntity(entity);
        return Result.ok("增加成功!");
    }
}
